<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'bas:mes:route:basMesRoute:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="85%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #basMesRouteOperList>
        <BasicTable
          @register="registerBasMesRouteOperTable"
          @row-click="handleBasMesRouteOperRowClick"
        >
          <template #sortUp="{ record }">
            <a @click="clickUp(record)" style="padding: 8px">
              <Icon icon="ant-design:arrow-up-outlined" size="18" color="#efbd47" />
            </a>
            <a @click="clickDown(record)">
              <Icon icon="ant-design:arrow-down-outlined" size="18" color="#efbd47" />
            </a>
          </template>
          <template #checkBox="{ record, column }">
            <a-checkbox v-model:checked="record[column.dataIndex]" />
            <!-- {{record[column.dataIndex]}} -->
          </template>
        </BasicTable>
        <a-button
          class="mt-2"
          @click="handleBasMesRouteOperAdd"
          v-auth="'bas:mes:route:basMesRoute:edit'"
        >
          <Icon icon="ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button>
      </template>
    </BasicForm>
    <ListSelect
      selectType="basMesRouteSelect"
      :checkbox="true"
      :params="queryParams"
      :selectList="listSelectRef"
      ref="routeSelectRef"
      @select="handSelect"
      v-show="false"
    />
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsBasMesRouteBasMesRouteForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasMesRoute, basMesRouteSave, basMesRouteForm } from '/@/api/bas/mes/route/basMesRoute';
  import { ListSelect } from '/@/components/ListSelect';
  import { basWorkShopTreeData } from '/@/api/bas/mes/workshop/basMesWorkShop';

  const emit = defineEmits(['success', 'register']);

  let listSelectRef = ref([]);
  let queryParams = ref({});
  let routeSelectRef = ref<any>(null);

  const { t } = useI18n('bas.mes.route.basMesRoute');
  const { showMessage } = useMessage();
  const record = ref<BasMesRoute>({} as BasMesRoute);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增工艺路线') : t('编辑工艺路线'),
  }));

  const isCopy = ref<boolean>(false);

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('工艺编码'),
      field: 'code',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      dynamicDisabled: true,
    },
    {
      label: t('工艺名称'),
      field: 'name',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      required: true,
    },
    {
      label: t('归属车间'),
      field: 'workShopCode',
      fieldLabel: 'workShop.name',
      component: 'TreeSelect',
      componentProps: {
        api: basWorkShopTreeData,
        params: { isShowCode: true },
        canSelectParent: false,
        allowClear: true,
      },
      required: true,
    },
    {
      label: t('产品名称'),
      field: 'invCode',
      fieldLabel: 'basInv.cinvname',
      component: 'ListSelect',
      // componentProps: {
      //   //maxlength: 100,
      //   selectType: 'basInvSelect',
      //   onSelect: (e) => {
      //     console.log(e, '==========');
      //   },
      // },
      componentProps: ({ formModel }) => {
        return {
          selectType: 'basInvSelect',
          onSelect: (e) => {
            console.log(e, '==========');
            formModel['basInv.taktTime'] = e[0].taktTime;
            formModel['basInv.proChangeTime'] = e[0].proChangeTime;
          },
        }
      },
      required: true,
    },
    {
      label: t('生产节拍（秒）'),
      field: 'basInv.taktTime',
      component: 'Input',
      componentProps: {},
      dynamicDisabled: true,
      // required: true,
    },
    {
      label: t('换产时间（分）'),
      field: 'basInv.proChangeTime',
      component: 'Input',
      componentProps: {},
      dynamicDisabled: true,
      // required: true,
    },
    {
      label: t('备注说明'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
      },
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('工艺明细'),
      field: 'basMesRouteOperList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'basMesRouteOperList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
    labelWidth: 150,
    schemas: inputFormSchemas,
    baseColProps: { lg: 24, md: 24 },
  });

  const [registerBasMesRouteOperTable, basMesRouteOperTable] = useTable({
    actionColumn: {
      width: 60,
      actions: (record: Recordable) => [
        {
          icon: 'ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handleBasMesRouteOperDelete.bind(this, record),
          },
          auth: 'bas:mes:route:basMesRoute:delete',
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
    showIndexColumn: true, //是否显示序列号
  });

  async function setBasMesRouteOperTableData(_res: Recordable) {
    basMesRouteOperTable.setColumns([
      {
        title: t('上移 / 下移'),
        slot: 'sortUp',
        width: 90,
        fixed: 'left',
      },
      {
        title: t('工序编码'),
        dataIndex: 'operCode',
        width: 100,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
        fixed: 'left',
      },
      {
        title: t('工序名称'),
        dataIndex: 'basOper.name',
        width: 120,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
        fixed: 'left',
      },
      {
        title: t('分派人数'),
        dataIndex: 'taskPleNum',
        width: 100,
        align: 'left',
        editRow: true,
        editComponent: 'InputNumber',
        editComponentProps: {
          min: 0,
          editDefaultValue: 1,
        },
        editDefaultValue: {
          taskPleNum: 1,
        },
        editable: true,
        editRule: (text: any, record: Recordable) => {
          return new Promise((resolve, reject) => {
            if (isNaN(text)) {
              reject('请输入数值');
            } else {
              resolve();
            }
          });
        },
      },
      {
        title: t('关键工序'),
        dataIndex: 'bkey',
        width: 120,
        align: 'center',
        slot: 'checkBox',
        // dictType: 'sys_yes_no',
        // editRow: true,
        // editComponent: 'Select',
        // editComponentProps: {
        //   dictType: 'sys_yes_no',
        //   allowClear: true,
        // },
        // editable: true,
        // editRule: true,
      },
      {
        title: t('计价方式'),
        dataIndex: 'costType',
        width: 120,
        align: 'center',
        dictType: 'mes_price_mode',
        editRow: true,
        editComponent: 'Select',
        editComponentProps: {
          dictType: 'mes_price_mode',
          allowClear: true,
        },
        editable: true,
        editRule: true,
      },
      {
        title: t('是否委外'),
        dataIndex: 'bout',
        width: 120,
        align: 'center',
        slot: 'checkBox',
        // dictType: 'sys_yes_no',
        // editRow: true,
        // editComponent: 'Select',
        // editComponentProps: {
        //   dictType: 'sys_yes_no',
        //   allowClear: true,
        // },
        // editable: true,
        // editRule: true,
      },
      {
        title: t('是否报工'),
        dataIndex: 'breport',
        width: 120,
        align: 'center',
        slot: 'checkBox',
        // dictType: 'sys_yes_no',
        // editRow: true,
        // editComponent: 'Select',
        // editComponentProps: {
        //   dictType: 'sys_yes_no',
        //   allowClear: true,
        // },
        // editable: true,
        // editRule: true,
      },
      {
        title: t('是否检验'),
        dataIndex: 'bcheck',
        width: 120,
        align: 'center',
        slot: 'checkBox',
        // dictType: 'sys_yes_no',
        // editRow: true,
        // editComponent: 'Select',
        // editComponentProps: {
        //   dictType: 'sys_yes_no',
        //   allowClear: true,
        // },
        // editable: true,
        // editRule: true,
      },
      {
        title: t('是否上机'),
        dataIndex: 'bmachine',
        width: 120,
        align: 'center',
        slot: 'checkBox',
        // dictType: 'sys_yes_no',
        // editRow: true,
        // editComponent: 'Select',
        // editComponentProps: {
        //   dictType: 'sys_yes_no',
        //   allowClear: true,
        // },
        // editable: true,
        // editRule: true,
      },
      {
        title: t('技能标准'),
        dataIndex: 'techLevel',
        width: 120,
        align: 'center',
        dictType: 'mes_tech_level',
        editRow: true,
        editComponent: 'Select',
        editComponentProps: {
          dictType: 'mes_tech_level',
          allowClear: true,
        },
        editable: true,
        editRule: true,
      },
      {
        title: t('技能控制'),
        dataIndex: 'techCtrl',
        width: 120,
        align: 'center',
        dictType: 'mes_tech_ctrl',
        editRow: true,
        editComponent: 'Select',
        editComponentProps: {
          dictType: 'mes_tech_ctrl',
          allowClear: true,
        },
        editable: true,
        editRule: true,
      },
      {
        title: t('报工方式'),
        dataIndex: 'reportType',
        width: 120,
        align: 'center',
        dictType: 'mes_report_type',
        editRow: true,
        editComponent: 'Select',
        editComponentProps: {
          dictType: 'mes_report_type',
          allowClear: true,
        },
        editable: true,
        editRule: true,
      },
      {
        title: t('计件单价'),
        dataIndex: 'iprice',
        width: 150,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {},
        editable: true,
        editRule: (text: any, record: Recordable) => {
          return new Promise((resolve, reject) => {
            if (isNaN(text)) {
              reject('请输入数值');
            } else {
              resolve();
            }
          });
        },
      },
      {
        title: t('工序说明'),
        dataIndex: 'remarks',
        width: 150,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 500,
        },
        editable: true,
        editRule: false,
      },
    ]);
    basMesRouteOperTable.setTableData(record.value.basMesRouteOperList || []);
  }

  function handleBasMesRouteOperRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handleBasMesRouteOperAdd() {
    routeSelectRef.value.openSelectModal();
  }

  function handleBasMesRouteOperDelete(record: Recordable) {
    basMesRouteOperTable.deleteTableDataRecord(record);
  }

  async function getBasMesRouteOperList() {
    let basMesRouteOperListValid = true;
    let basMesRouteOperList: Recordable[] = [];
    for (const record of basMesRouteOperTable.getDataSource()) {
      console.log(record, 'record====');
      if (!(await record.onEdit?.(false, true))) {
        basMesRouteOperListValid = false;
      }
      if (isCopy.value) {
        record.isNewRecord = true;
        record.id = '';
      }
      basMesRouteOperList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of basMesRouteOperTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      if (isCopy.value) {
        record.isNewRecord = true;
        record.id = '';
      }
      basMesRouteOperList.push({
        ...record,
        status: '1',
      });
    }
    if (!basMesRouteOperListValid) {
      throw { errorFields: [{ name: ['basMesRouteOperList'] }] };
    }
    return basMesRouteOperList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    // basMesRouteOperList
    const res = await basMesRouteForm(data);
    console.log('res==', res);
    record.value = (res.basMesRoute || {}) as BasMesRoute;
    record.value.__t = new Date().getTime();
    record.value.basMesRouteOperList = res.basMesRoute.basMesRouteOperList.map(item => {
      item.bout = item.bout == '1' ? true : false;
      item.breport = item.breport == '1' ? true : false;
      item.bcheck = item.bcheck == '1' ? true : false;
      item.bmachine = item.bmachine == '1' ? true : false;
      item.bkey = item.bkey == '1' ? true : false;
      return item;
    });
    if (data.isCopy) {
      isCopy.value = true;
      record.value.id = '';
      record.value.invCode = '';
      record.value.basInv.cinvname = '';
      record.value.code = '';
    }
    setFieldsValue(record.value);
    setBasMesRouteOperTableData(res);
    setDrawerProps({ loading: false });
  });

  // 工序选择
  function handSelect(selectData) {
    selectData.forEach((item) => {
      basMesRouteOperTable.insertTableDataRecord({
        id: new Date().getTime(),
        isNewRecord: true,
        editable: true,
        operCode: item.code,
        basOper: { name: item.name },
        bkey: item.bkey,
        costType: item.costType,
        bout: item.bout,
        breport: item.breport,
        bcheck: item.bcheck,
        bmachine: item.bmachine || '0',
        techLevel: item.techLevel,
        techCtrl: item.techCtrl,
        reportType: item.reportType,
        taskPleNum: 1,
      });
    });
  }

  function clickUp(record) {
    // 上移
    let arr = basMesRouteOperTable.getDataSource();
    let index = -1;
    for (var i = 0; i < arr.length; i++) {
      if (arr[i].id == record.id) {
        index = i;
        break;
      }
    }
    if (index === 0) {
      return false;
    }
    arr.splice(index - 1, 1, ...arr.splice(index, 1, arr[index - 1]));
    basMesRouteOperTable.setTableData(arr || []);
  }

  // 下移
  function clickDown(record) {
    let arr = basMesRouteOperTable.getDataSource();
    let index = -1;
    for (var i = 0; i < arr.length; i++) {
      if (arr[i].id == record.id) {
        index = i;
        break;
      }
    }
    if (index === arr.length - 1) {
      return false;
    }
    arr.splice(index, 1, ...arr.splice(index + 1, 1, arr[index]));
    basMesRouteOperTable.setTableData(arr || []);
  }

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        code: record.value.code,
      };
      data.basMesRouteOperList = await getBasMesRouteOperList();
      data.basMesRouteOperList.forEach((item) => {
        item.bkey = item.bkey ? '1' : '0';
        item.bout = item.bout ? '1' : '0';
        item.breport = item.breport ? '1' : '0';
        item.bcheck = item.bcheck ? '1' : '0';
        item.bmachine = item.bmachine ? '1' : '0';
      });

      // console.log('submit', params, data, record);
      const res = await basMesRouteSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>

<style>
  .jeesite-editable-cell__action {
    display: none;
  }
  /* .ant-select-show-search {
    width: 100% !important ;
  } */
  .edit-cell-align-center {
    width: 100% !important;
  }
  .edit-cell-align-right {
    width: 100% !important;
  }
  .edit-cell-align-left {
    width: 100% !important;
  }
</style>
